package com.example;

import com.example.request.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.concurrent.Callable;

public class RpcHandler extends SimpleChannelInboundHandler<String> implements Callable {

    private ChannelHandlerContext context;
    private RpcRequest request;
    private String result;



    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        this.context = ctx;
    }

    @Override
    public synchronized Object call() throws Exception {
        context.writeAndFlush(request); // 发送请求
        System.out.println("send request");
        wait(1000L); // 等待结果返回
        return result;
    }

    @Override
    protected synchronized void channelRead0(ChannelHandlerContext ctx, String msg) {
        result = msg;
        notifyAll();
    }

    /**
     * 释放锁，防止线程一直阻塞
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        System.out.println("exception ...");
        result = null;
        notifyAll();
    }

    public void setRequest(RpcRequest request) {
        this.request = request;
    }
}
